package net;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Vector;

import ae_server.*;

public class TCP_MultiThreadServer extends Thread
{
	private static int MAX_CLIENTS;
	private static int clientsOnline=0;
	private static ServerSocket serverSocket;
	private static boolean Active=true;
	
	private Socket clientSocket = null;
	
	private static aeTempClientHandler TempClientHandler = null;
	
	public static Vector<TCP_ServerClient> tempClients = new Vector<TCP_ServerClient>();
	
	public synchronized void start(int port, int max_clients)
	{
		Active=true;
		MAX_CLIENTS=max_clients;
		tempClients.clear();
		TempClientHandler = new aeTempClientHandler();
		TempClientHandler.start();
		try
		{
			serverSocket = new ServerSocket(port);
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		super.start();
	}
	
	public void run()
	{
		System.out.println("Server is running. Port = "+serverSocket.getLocalPort()+". Capacity = "+MAX_CLIENTS+".");
		while(Active)
		{
			try
			{
				clientSocket = serverSocket.accept();
				System.out.println("Incoming connection from "+clientSocket.getInetAddress().toString());
				tempClients.add(new TCP_ServerClient(clientSocket));
				tempClients.lastElement().start();
				tempClients.lastElement().SendMessage("INFO", clientsOnline+"|"+MAX_CLIENTS);
				System.out.println("New temporary client accepted");
			} catch (IOException e)
			{
				// TODO Auto-generated catch block
				System.out.println(e.getMessage());
			}
		}			
	}
	
	public void shutdown()
	{
		Active=false;
		try
		{
			if(!serverSocket.isClosed())
				serverSocket.close();
		} catch (IOException e)
		{
			e.printStackTrace();
		}
		TempClientHandler.StopHandling();
		TempClientHandler=null;
		serverSocket=null;
		for (TCP_ServerClient cl : tempClients)
		{
			cl.closeConnection();
		}
		tempClients.clear();
		System.out.println("Server stopped successfully.");
	}
}
